package com.hao.tool.web.module.fileInfo.controller;

import cn.hutool.core.io.FileUtil;
import com.hao.tool.web.component.exception.ErrorEnum;
import com.hao.tool.web.component.exception.ErrorPageException;
import com.hao.tool.web.module.fileInfo.entity.FileInfo;
import com.hao.tool.web.module.fileInfo.service.FileInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.OutputStream;

/**
 * description
 *
 * @author RuiHaoZ on CMHK.jx
 * @date 2020-07-10 22:33
 */
@RestController
@RequestMapping("/rest/image")
public class ImageRestController {

    public static final String SEE_PATH = "/rest/image/info/{id}";

    @Autowired
    private FileInfoService fileInfoService;


    @GetMapping("/info/{fileId}")
    public void downInfo(@PathVariable String fileId,
                         HttpServletResponse response) throws Exception {
        FileInfo fileInfo = fileInfoService.getById(fileId);

        if (fileInfo == null) {
            throw new ErrorPageException(ErrorEnum.NOT_FOUNT, "文件内容不存在");
        } else {
            String downFilePath = fileInfo.getFilePath();
            File downFile = new File(downFilePath);
            if (!downFile.exists()) {
                throw new ErrorPageException(ErrorEnum.NOT_FOUNT, "文件不存在");
            }
            byte[] bs = FileUtil.readBytes(downFilePath);
            OutputStream outputStream = response.getOutputStream();
            response.setContentType("image/jpeg");
            outputStream.write(bs);
            outputStream.close();
        }
    }


}
